import * as OTPAuth from 'otpauth';

/**
 * 生成TOTP验证码
 */
export function generateTOTP(secret, options = {}) {
  const totp = new OTPAuth.TOTP({
    secret: OTPAuth.Secret.fromBase32(secret),
    algorithm: options.algorithm || 'SHA1',
    digits: options.digits || 6,
    period: options.period || 30,
  });
  
  return totp.generate();
}

/**
 * 获取剩余时间（秒）
 */
export function getTimeRemaining(period = 30) {
  const now = Math.floor(Date.now() / 1000);
  return period - (now % period);
}

/**
 * 格式化验证码（添加空格分隔）
 */
export function formatCode(code) {
  if (code.length === 6) {
    return `${code.slice(0, 3)} ${code.slice(3)}`;
  }
  if (code.length === 8) {
    return `${code.slice(0, 4)} ${code.slice(4)}`;
  }
  return code;
}

/**
 * 解析TOTP URI
 */
export function parseTOTPUri(uri) {
  try {
    const totp = OTPAuth.URI.parse(uri);
    return {
      type: totp.constructor.name.toLowerCase(),
      issuer: totp.issuer,
      label: totp.label,
      secret: totp.secret.base32,
      algorithm: totp.algorithm,
      digits: totp.digits,
      period: totp.period,
    };
  } catch (error) {
    throw new Error('Invalid TOTP URI');
  }
}

/**
 * 生成TOTP URI（用于二维码）
 */
export function generateTOTPUri(options) {
  const totp = new OTPAuth.TOTP({
    issuer: options.issuer || '2FA Manager',
    label: options.label || options.accountName,
    secret: OTPAuth.Secret.fromBase32(options.secret),
    algorithm: options.algorithm || 'SHA1',
    digits: options.digits || 6,
    period: options.period || 30,
  });
  
  return totp.toString();
}


